package com.lijie.ljblog.config;

import com.lijie.ljblog.common.exception.TokenException;
import com.lijie.ljblog.model.Person;
import com.lijie.ljblog.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class UploadImgInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    /**
     * Controller方法处理之前
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        boolean result = false;
        log.info("进拦截器");
        //从请求头中取出token
        String token = request.getHeader("Authorization");
        if(token == null){//如果有token则验证
            throw new TokenException("token为空");
        }
        Person person = jwtUtil.parseToken(token);
        if(!ObjectUtils.isEmpty(person)){
            result=true;
        }else {
            throw new TokenException("权限不足");
        }
        return result;
    }

    /**
     * 视图渲染之后的操作
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

    /**
     * Controller方法处理完之后，DispatcherServlet进行视图的渲染之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }
}
